﻿using Susha.Models.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Susha.Models;
using Susha.Models.Helpers;
using System.Text.RegularExpressions;
using System.Web.Security;
using System.Web.Script.Serialization;

namespace Susha.Areas.Default.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /Default/User/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View(new UserLoginPage());
        }
        
        [HttpPost]
        public ActionResult Login(UserClass user)
        {
            if (ModelState.IsValid)
            {
                UserClass userFromDB = UserRepository.Login(user.Email, user.Password);
                if (userFromDB != null)
                {
                    UserSerializeModel serializeModel = new UserSerializeModel();
                    serializeModel.UserId = userFromDB.Id;
                    serializeModel.Email = userFromDB.Email;
                    serializeModel.Role = userFromDB.Role;

                    JavaScriptSerializer serializer = new JavaScriptSerializer();

                    String userData = serializer.Serialize(serializeModel);

                    FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(
                        1,
                        userFromDB.Email,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(15),
                        false,
                        userData);

                    String encTicket = FormsAuthentication.Encrypt(authenticationTicket);
                    HttpCookie cookie = new HttpCookie(CommonTools.COOKIE_NAME, encTicket);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    Response.Cookies.Set(cookie);

                    return RedirectToAction("Index", "Home");
                }

                ModelState.AddModelError("Password", "Пароль неверен");

            }

            return View(new UserLoginPage(user));
        }

        [HttpGet]
        public ActionResult Register()
        {
            UserRegisterPage page = new UserRegisterPage();
            
            CreateCaptcha(page);

            return View(page);
        }

        [HttpPost]
        public ActionResult Register(UserRegistrationView user)
        {
            // Verify Email
            if (user.Email != null)
            {
                // Does user exists or not
                if (UserRepository.IsUserExisting(user.Email))
                {
                    ModelState.AddModelError("Email", "Пользователь уже существует"); // "User already exists"
                }
                
                // Does Email has correct format?
                Regex reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.Compiled);
                Match match = reg.Match(user.Email);
                if (!match.Success)
                {
                    ModelState.AddModelError("Email", "Неверная почта"); // "Incorrect email"
                }
            }

            // Captcha
            if (String.IsNullOrWhiteSpace(user.Captcha) || user.Captcha != null && !user.Captcha.Equals(Session["Captcha"]))
            {
                ModelState.AddModelError("Captcha", "Captcha is not correct");
            }

            if (ModelState.IsValid)
            {
                UserRepository.Save(user.Convert2UserClass());
                return RedirectToAction("Index", "Home");
            }

            UserRegisterPage page = new UserRegisterPage();
            page.User = user;
            CreateCaptcha(page);

            return View(page);
        }

        public ActionResult LogOut()
        {
            //FormsAuthentication.SignOut();
            Response.Cookies.Set(new HttpCookie(CommonTools.COOKIE_NAME, String.Empty));
            return RedirectToAction("Index", "Home");
        }

        private void CreateCaptcha(UserRegisterPage page)
        {
            Tuple<String, String> captcha = CommonTools.GetCaptcha();
            Session["Captcha"] = captcha.Item2;
            page.FalseCaptcha = captcha.Item1;
        }
    }
}
